import { getCurrentInstance, h } from 'vue';
import type { MenuOptions, MenuItem } from '@imengyu/vue3-context-menu';
import { useEditorStore } from '@/stores/editorStore';
import { useSettingsStore } from '@/stores/settingsStore';
import { useVueFlow, type NodeMouseEvent } from '@vue-flow/core';
import { 
    generateXmlSnippet, 
    nodeToJson, 
    nodeWithChildrenToJson, 
    copyToClipboard, 
    convertToJsonString, 
    convertToYamlString, 
    convertToTomlString 
} from '@/utils/exportUtils';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ref, computed, reactive } from 'vue';
import { Delete, Expand, CircleClose, DocumentCopy } from '@element-plus/icons-vue';

export function useContextMenu() {
    const instance = getCurrentInstance();
    const $contextmenu = instance?.appContext.config.globalProperties.$contextmenu;
    const jdfStore = useEditorStore();
    const settingsStore = useSettingsStore();
    const { fitView } = useVueFlow(); // Get fitView if needed for pane menu

    // --- Menu Item Generation --- 

    const createCopyMenuItem = (label: string, format: string, generator: () => string | null) => ({
        label,
        onClick: () => {
            const content = generator();
            if (content) {
                copyToClipboard(content, format);
            } else {
                 console.error('Failed to generate content for copying');
            }
        }
    });

    const createNestedCopyMenu = (nodeId: string): MenuItem | null => {
        const nodes = jdfStore.flowElements.nodes;
        const edges = jdfStore.flowElements.edges;
        const node = nodes.find(n => n.id === nodeId);
        if (!node) return null;

        const nodeOnlyJson = () => nodeToJson(nodes, nodeId);
        const nodeWithChildrenJson = () => nodeWithChildrenToJson(nodes, edges, nodeId);

        // Correctly return a MenuItem object with label and children
        return {
            label: '复制为...', 
            icon: () => h(DocumentCopy), // Render icon using h()
            children: [
                // XML/JDF
                createCopyMenuItem('XML (本节点)', 'XML', () => generateXmlSnippet(nodes, edges, nodeId, false)),
                createCopyMenuItem('XML (含子节点)', 'XML', () => generateXmlSnippet(nodes, edges, nodeId, true)),
                { divided: true },
                // JSON
                createCopyMenuItem('JSON (本节点)', 'JSON', () => convertToJsonString(nodeOnlyJson())),
                createCopyMenuItem('JSON (含子节点)', 'JSON', () => convertToJsonString(nodeWithChildrenJson())),
                 { divided: true },
                // YAML
                 createCopyMenuItem('YAML (本节点)', 'YAML', () => convertToYamlString(nodeOnlyJson())),
                 createCopyMenuItem('YAML (含子节点)', 'YAML', () => convertToYamlString(nodeWithChildrenJson())),
                 { divided: true },
                 // TOML
                 createCopyMenuItem('TOML (本节点)', 'TOML', () => convertToTomlString(nodeOnlyJson())),
                 createCopyMenuItem('TOML (含子节点)', 'TOML', () => convertToTomlString(nodeWithChildrenJson())),
            ]
        };
    };

    // --- Helper for Add Child Node --- 
    const promptForNodeName = async (parentId: string) => {
        try {
            const { value } = await ElMessageBox.prompt(
                '请输入新子节点的名称 (例如: ResourceLink, Intent, etc.):',
                '添加子节点',
                {
                    confirmButtonText: '添加',
                    cancelButtonText: '取消',
                    inputPattern: /^[a-zA-Z0-9_\-]+$/,
                    inputErrorMessage: '无效的节点名称 (允许字母, 数字, _, -)',
                }
            );
            // User confirmed and input is valid
            jdfStore.addChildNode({ parentId, newNodeName: value });
            if (jdfStore.error) {
                ElMessage.error(`添加失败: ${jdfStore.error}`);
            }
             else {
                 ElMessage.success(`子节点 "${value}" 已添加`);
            }
        } catch {
            // User cancelled
            ElMessage.info('添加操作已取消');
        }
    };

    // --- Context Menu Handlers --- 

    const onNodeContextMenu = (event: any) => { // Use any for the custom event from JDFNode
        if (event.event && typeof event.event.preventDefault === 'function') event.event.preventDefault();
        if (event.event && typeof event.event.stopPropagation === 'function') event.event.stopPropagation();

        const node = event.node;
        if (!node || !node.id) return;

        jdfStore.selectNodeVisually(node.id); // Select visually only

        let clientX = 0, clientY = 0;
        if (event.event instanceof MouseEvent) {
            clientX = event.event.clientX; clientY = event.event.clientY;
        } else if (event.event instanceof TouchEvent && event.event.touches.length > 0) {
            clientX = event.event.touches[0].clientX; clientY = event.event.touches[0].clientY;
        }

        const menuItems: MenuOptions['items'] = [];

        // Expand/Collapse options
        if (node.data.hasChildren) {
            menuItems.push(
                { label: "展开所有子节点", onClick: () => jdfStore.expandAllChildren(node.id) },
                { label: "折叠所有子节点", onClick: () => jdfStore.collapseAllChildren(node.id) }
            );
        }

        // --- Add Child Option --- 
        if (menuItems.length > 0) menuItems.push({ divided: true });
        menuItems.push({
            label: "添加子节点...",
            onClick: () => promptForNodeName(node.id)
        });
        // --- End Add Child Option --- 

        // --- Add Delete Option --- 
        menuItems.push({ divided: true }); // Separator before delete
        menuItems.push({
            label: "删除节点 (及子节点)",
            onClick: () => {
                ElMessageBox.confirm(
                    `确定要删除节点 <${node.data.nodeName}> 及其所有子节点吗？此操作无法撤销。`,
                    '删除节点',
                    {
                        confirmButtonText: '确定删除',
                        cancelButtonText: '取消',
                        type: 'error', // Use error type for destructive action
                        dangerouslyUseHTMLString: true // Allow HTML in message
                    }
                ).then(() => {
                    jdfStore.deleteNodeWithDescendants(node.id);
                    ElMessage.success('节点已删除');
                }).catch(() => {
                    ElMessage.info('删除操作已取消。');
                });
            }
        });
        // --- End Delete Option ---

        // Copy options (nested)
        const copyMenu = createNestedCopyMenu(node.id);
        if (copyMenu) {
            if (menuItems.length > 0) menuItems.push({ divided: true });
            menuItems.push(copyMenu);
        }

        // Show menu
        if (menuItems.length > 0 && $contextmenu) {
            const menuOptions: MenuOptions = {
                items: menuItems,
                x: clientX,
                y: clientY,
                theme: settingsStore.darkMode ? 'dark' : 'light',
            };
            console.log('Showing node context menu with options:', menuOptions);
            $contextmenu(menuOptions);
        }
    };

    const onPaneContextMenu = (event: MouseEvent) => {
        event.preventDefault();
        event.stopPropagation();

        const menuItems: MenuOptions['items'] = [
            { label: "适应视图", onClick: () => fitView({ padding: 0.2 }) }
            // Add other global graph options here
        ];

        if ($contextmenu) {
            const menuOptions: MenuOptions = {
                items: menuItems,
                x: event.clientX,
                y: event.clientY,
                theme: settingsStore.darkMode ? 'dark' : 'light',
            };
             console.log('Showing pane context menu with options:', menuOptions);
            $contextmenu(menuOptions);
        }
    };

    // Return the handlers to be used in the component
    return {
        onNodeContextMenu,
        onPaneContextMenu
    };
} 